package com.nifostasky.blog.controller;

import com.nifostasky.entity.ScheduleJob;
import com.nifostasky.service.ScheduleJobService;
import com.nifostasky.blog.utils.QuartzUtils;
import org.quartz.Scheduler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import lombok.AllArgsConstructor;

/**
 * 定时任务(ScheduleJob)表控制层
 *
 * @author makejava
 * @since 2022-03-08 17:21:13
 */
@RestController
@RequestMapping("/blog")
@AllArgsConstructor
public class ScheduleJobController {
    //注入任务,从数据库中获取
    @Autowired
    private ScheduleJobService schedulerService;
    //注入任务调度
    @Autowired
    private Scheduler scheduler;

    /**
     * 开始任务
     * @param taskId
     * @return
     */
    @GetMapping("/createJob")
    public String createJob(Long taskId)  {
        try {
            //执行任务命令
            ScheduleJob scheduleJob = schedulerService.getById(taskId);
            QuartzUtils.createScheduleJob(scheduler,scheduleJob);
        } catch (Exception e) {
            return "创建失败";
        }
        return "创建成功";
    }

    /**
     * 停止任务
     * @param taskId
     * @return
     */
    @RequestMapping("/pauseJob")
    public String  pauseJob(Long taskId)  {
        try {
            ScheduleJob scheduleJob = schedulerService.getById(taskId);
            QuartzUtils.pauseScheduleJob (scheduler,taskId.toString());
        } catch (Exception e) {
            return "暂停失败";
        }
        return "暂停成功";
    }

    /**
     * 立即运行一个任务
     * @return
     */
    @RequestMapping("/runOnce")
    public String  runOnce(Long taskId)  {
        try {
            ScheduleJob scheduleJob = schedulerService.getById(taskId);
            QuartzUtils.runOnce (scheduler,taskId.toString());
        } catch (Exception e) {
            return "运行一次失败";
        }
        return "运行一次成功";
    }

    /**
     * 启动任务
     * @return
     */
    @RequestMapping("/resume")
    public String  resume(Long taskId)  {
        try {
            ScheduleJob scheduleJob = schedulerService.getById(taskId);
            QuartzUtils.resumeScheduleJob(scheduler,taskId.toString());
        } catch (Exception e) {
            return "启动失败";
        }
        return "启动成功";
    }

    /**
     * 修改任务
     * @param scheduleJob
     * @return
     */
    @RequestMapping("/update")
    public String  update(ScheduleJob scheduleJob)  {
        try {
            //进行测试所以写死
            schedulerService.updateById(scheduleJob);
            QuartzUtils.updateScheduleJob(scheduler,scheduleJob);
        } catch (Exception e) {
            return "启动失败";
        }
        return "启动成功";
    }
}
